package com.sdhs.paas.itims.app;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.TypeReference;
import com.sdhs.paas.itims.bean.AppInfoFileBean;
import com.sdhs.paas.itims.bean.VersionPublishBean;
import com.sdhs.paas.itims.bean.VersionPublishDetailBean;
import com.sdhs.paas.itims.configuration.Config;
import com.sdhs.paas.itims.dto.DeviceUpgradeDTO;
import com.sdhs.paas.itims.dto.VersionPublishDTO;
import com.sdhs.paas.itims.dto.req.DeviceUpgradeReqDTO;
import com.sdhs.paas.itims.dto.req.VersionPublishReqDTO;
import com.sdhs.paas.itims.dto.res.VersionPublishResDTO;
import com.sdhs.paas.itims.service.AppInfoFileService;
import com.sdhs.paas.itims.service.VersionPublishDetailService;
import com.sdhs.paas.itims.service.VersionPublishService;
import com.sdhs.paas.sdk.base.common.BasePage;
import com.sdhs.paas.sdk.base.dto.PageInfoDTO;
import com.sdhs.paas.sdk.base.page.Page;
import com.sdhs.paas.sdk.base.utils.EntityDtoConvertUtil;
import com.sdhs.paas.sdk.core.PaasBaseException;
import com.sdhs.paas.sdk.core.PaasBaseRequest;
import com.sdhs.paas.sdk.core.PaasBaseResponse;
import com.sdhs.paas.sdk.core.RefreshableRestController;
import com.sdhs.paas.sdk.core.logger.Logger;
import com.sdhs.paas.sdk.core.logger.LoggerFactory;
import com.sdhs.paas.sdk.core.web.client.PaasRestTemplate;

/**
 * @author VersionPublish
 * @version 1.0
 * @Title:  代码生成接口，用于接受前端传输过来的数据
 * @author kangjichang
 * @date 2018-09-18
 */
 
@RefreshableRestController
@RequestMapping(value = "/versionPublish")
public class VersionPublishController {
	private static Logger LOGGER  = LoggerFactory.getLogger(VersionPublishController.class); 
	
    @Autowired
    private VersionPublishService versionPublishService;
    
    @Autowired
    private VersionPublishDetailService versionPublishDetailService;
    
    @Autowired
    private AppInfoFileService appInfoFileService;
    
    @Autowired
	@Qualifier("externalRestTemplate")
	private PaasRestTemplate externalRestTemplate; 
    
    @Autowired
	Config config;
    
    /**
     * 分页查询接口
     * */
    @PostMapping("/getVersionPublishPageList")
	public PaasBaseResponse<VersionPublishResDTO> getVersionPublishPageList(@RequestBody PaasBaseRequest<VersionPublishReqDTO> versionPublishReqDTO) {
    	VersionPublishDTO versionPublishDTO = versionPublishReqDTO.getBody().getVersionPublishDTO();
    	PageInfoDTO pageInfoDTO = versionPublishReqDTO.getBody().getPageInfo();
    	
		BasePage pageRequest = new BasePage();
		pageRequest.setPage(pageInfoDTO.getPage());
		pageRequest.setCount(pageInfoDTO.getPageSize());
    	
		VersionPublishBean versionPublishBean = EntityDtoConvertUtil.convertToEntity(versionPublishDTO, VersionPublishBean.class);
    	Page<VersionPublishBean> page = versionPublishService.getPageVersionPublishList(pageRequest, versionPublishBean);
    	PageInfoDTO resPageInfoDTO = new PageInfoDTO();
    	VersionPublishResDTO versionPublishResDTO = new VersionPublishResDTO();
    	resPageInfoDTO.setPage(page.getCurPage());
		resPageInfoDTO.setPageSize(page.getPageSize());
		resPageInfoDTO.setPageCount(page.getPageCount());
		resPageInfoDTO.setRowCount(page.getTotalCount());
		versionPublishResDTO.setPageInfo(resPageInfoDTO);
		List<VersionPublishBean> versionPublishBeanList = page.getResult();
		List<VersionPublishDTO> dtoList = new ArrayList<VersionPublishDTO>();
		dtoList = EntityDtoConvertUtil.convertToDTOList(versionPublishBeanList, new TypeReference<List<VersionPublishDTO>>() {
		});
		versionPublishResDTO.setVersionPublishDTOList(dtoList);
    	return new PaasBaseResponse<>(versionPublishResDTO);
	}
	
	/**
	 * 保存接口
	 * */
	@PostMapping("/saveVersionPublish")
	public PaasBaseResponse<VersionPublishResDTO> saveVersionPublish(@RequestBody PaasBaseRequest<VersionPublishReqDTO> versionPublishReqDTO) {
		VersionPublishDTO versionPublishDTO = versionPublishReqDTO.getBody().getVersionPublishDTO();
		VersionPublishBean versionPublishBean = EntityDtoConvertUtil.convertToEntity(versionPublishDTO, VersionPublishBean.class);
		List<String> equipmentList = versionPublishDTO.getEquipmentList();
		String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
		versionPublishBean.setId(uuid);
		versionPublishBean.setIsDeleted(0);
		
		List<VersionPublishDetailBean> versionPublishDetailBeanList = new ArrayList<VersionPublishDetailBean>();
		VersionPublishDetailBean versionPublishDetailBean = null;
		String resutlt = "0000";
		if(equipmentList != null && equipmentList.size() > 0 ){
			for(String str : equipmentList){
				versionPublishDetailBean = new VersionPublishDetailBean();
				versionPublishDetailBean.setEquipmentSyn(str);
				versionPublishDetailBean.setVersionPublishId(uuid);
				versionPublishDetailBean.setAppFileId(versionPublishDTO.getFileId());
				versionPublishDetailBean.setId(UUID.randomUUID().toString().trim().replaceAll("-", ""));
				versionPublishDetailBean.setIsDeleted(0);
				versionPublishDetailBean.setStatus(0);
				//应用文件升级推送接口,调用nettyserver接口进行推送
				resutlt = sendUpgrade(versionPublishDetailBean);
				if(!"0000".equals(resutlt)){
					LOGGER.info("升级推送失败，调用nettyserver接口失败！");
					throw new PaasBaseException("000001", "升级推送失败,调用nettyserver"+config.nettyServerUrl+"/api/pos/version"+"接口失败！");
				}
				versionPublishDetailBeanList.add(versionPublishDetailBean);
			}
		}
		//保存发布主表信息
		Boolean flag = versionPublishService.saveVersionPublish(versionPublishBean);
		//保存发布详情信息
		flag = versionPublishDetailService.saveVersionPublishDetailList(versionPublishDetailBeanList);
		if(!flag){
			throw new PaasBaseException("500", "保存发布信息失败！");
		}
		versionPublishDTO.setId(uuid);
		VersionPublishResDTO versionPublishResDTO = new VersionPublishResDTO();
		versionPublishResDTO.setVersionPublishDTO(versionPublishDTO);
		return new PaasBaseResponse<>(versionPublishResDTO);
	}
	
	/**
	 * 修改接口
	 * */
	@PostMapping("/updateVersionPublish")
	public PaasBaseResponse<VersionPublishResDTO> updateVersionPublish(@RequestBody PaasBaseRequest<VersionPublishReqDTO> versionPublishReqDTO) {
		VersionPublishDTO versionPublishDTO = versionPublishReqDTO.getBody().getVersionPublishDTO();
		VersionPublishBean versionPublishBean = EntityDtoConvertUtil.convertToEntity(versionPublishDTO, VersionPublishBean.class);
		Boolean flag = versionPublishService.updateVersionPublish(versionPublishBean);
		VersionPublishResDTO versionPublishResDTO = new VersionPublishResDTO();
		versionPublishResDTO.setVersionPublishDTO(versionPublishDTO);
		return new PaasBaseResponse<>(versionPublishResDTO);
	}
	
	/**
	 * 获取详情接口
	 * */
	@PostMapping("/getVersionPublishDetail")
	public PaasBaseResponse<VersionPublishResDTO> getVersionPublishDetail(@RequestBody PaasBaseRequest<VersionPublishReqDTO> versionPublishReqDTO) {
		VersionPublishDTO versionPublishDTO = versionPublishReqDTO.getBody().getVersionPublishDTO();
		VersionPublishBean versionPublishBean = EntityDtoConvertUtil.convertToEntity(versionPublishDTO, VersionPublishBean.class);
		versionPublishBean = versionPublishService.getVersionPublishDetail(versionPublishBean.getId());
		versionPublishDTO = EntityDtoConvertUtil.convertToDTO(versionPublishBean, VersionPublishDTO.class);
		VersionPublishResDTO versionPublishResDTO = new VersionPublishResDTO();
		versionPublishResDTO.setVersionPublishDTO(versionPublishDTO);
		return new PaasBaseResponse<>(versionPublishResDTO);
	}
	
	/**
	 * 删除接口
	 * */
	@PostMapping("/deleteVersionPublish")
	public PaasBaseResponse<VersionPublishResDTO> deleteVersionPublish(@RequestBody PaasBaseRequest<VersionPublishReqDTO> versionPublishReqDTO) {
		VersionPublishDTO versionPublishDTO = versionPublishReqDTO.getBody().getVersionPublishDTO();
		VersionPublishBean versionPublishBean = EntityDtoConvertUtil.convertToEntity(versionPublishDTO, VersionPublishBean.class);
		Boolean flag = versionPublishService.deleteVersionPublish(versionPublishBean);
		VersionPublishResDTO versionPublishResDTO = new VersionPublishResDTO();
		return new PaasBaseResponse<>(versionPublishResDTO);
	}
	
	private String sendUpgrade(VersionPublishDetailBean versionPublishDetailBean){
		String device_id = versionPublishDetailBean.getEquipmentSyn();
		String fileId = versionPublishDetailBean.getAppFileId();
		AppInfoFileBean appInfoFileBean = appInfoFileService.getAppInfoFileDetail(fileId);
		String url = config.fileDownloadUrl+"?id="+appInfoFileBean.getFileStoreId();
		String hashcode = appInfoFileBean.getHashCode();
		String version = appInfoFileBean.getFileVersion();
		DeviceUpgradeReqDTO duDTO = new DeviceUpgradeReqDTO();
		duDTO.setDevice_id(device_id);
		DeviceUpgradeDTO deviceUpgradeDTO = new DeviceUpgradeDTO();
		deviceUpgradeDTO.setUrl(url);
		deviceUpgradeDTO.setHashcode(hashcode);
		deviceUpgradeDTO.setVersion(version);
		duDTO.setData(deviceUpgradeDTO);
		ModelMap objRest = null;
		try{
			objRest = externalRestTemplate.postForObject(config.nettyServerUrl+"/api/pos/version", duDTO, ModelMap.class);
		}catch(Exception e){
			return "9999";
		}
		String code = objRest.get("code")+"";
		String msg = objRest.get("objRest")+"";
		return code;
	}
}
